'''
-------------------------------------------------------------------------------
pyql.py v0.1
Release Date: 12 Aug 2010
-------------------------------------------------------------------------------

The module provides Python API to retreive stock information from Yahoo! Finance
using Yahoo Query Language.

The module uses Yahoo Query API, and sends REST to retrieve JSON, then converts
the result in a list of dictionary objects, and returns it.


Basic Usage:
   >>> import pyql
   >>> tickers = ['FFIV', 'MSFT', 'GOOG']
   >>> print pyql.lookup(tickers)
   >>> tickers = ['AAPL']
   >>> print pyql.lookup(tickers)

To clone the project:
   hg clone https://pyql.googlecode.com/hg/ pyql  
-------------------------------------------------------------------------------
SOFTWARE LICENSE

Copyright (c) 2010 Minn Myat Soe

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
------------------------------------------------------------------------------- 
'''
import urllib2
import json

class Pyql:
    pass

def lookup(symbols):
    # construct Yahoo Query Language statement
    yql = "select * from yahoo.finance.quotes where symbol in ('%s')" % "', '".join( symbols) 
    
    # construct REST query                        
    url = "http://query.yahooapis.com/v1/public/yql?q=" \
            + urllib2.quote( yql ) \
            + "&format=json&env=http%3A%2F%2Fdatatables.org%2Falltables.env&callback="
    
    try: 
        result = urllib2.urlopen(url)
    except urllib2.HTTPError, e:        
        raise e        
    except urllib2.URLError, e:
        raise e
       
    data = json.loads( result.read() )
    jsonQuotes = data['query']['results']['quote']
    
    # To make sure the function returns a list
    pythonQuotes = []
    if type( jsonQuotes ) == type ( dict() ):
        pythonQuotes.append( jsonQuotes )
    else:
        pythonQuotes = jsonQuotes
    
    return pythonQuotes
   